using Digitalmes.Domain.Entities.Mes.Masters;

namespace Digitalmes.Application.Mes.Masters.Workshops.Commands;

/// <summary>
/// 更新车间信息命令。
/// </summary>
public record UpdateWorkshopCommand(long Id, MdWorkshopDto Workshop) : IRequest<IResult<bool>>;

internal sealed class UpdateWorkshopCommandHandler(IRepository<MdWorkshop> repo) : IRequestHandler<UpdateWorkshopCommand, IResult<bool>>
{
    public async Task<IResult<bool>> Handle(UpdateWorkshopCommand request, CancellationToken cancellationToken)
    {
        // 检查编号是否已存在。
        if (await repo.IsAnyAsync(m => m.WspCode == request.Workshop.WspCode && m.Id != request.Id, cancellationToken))
        {
            return Result.Failure("车间编号已存在");
        }

        var workshop = await repo.GetByIdAsync(request.Id, cancellationToken);
        if (workshop == null)
        {
            return Result.Failure("未找到要更新的车间");
        }

        workshop.WspName = request.Workshop.WspName;
        workshop.Remark = request.Workshop.Remark;
        workshop.Status = request.Workshop.Status;

        var ok = await repo.UpdateAsync(workshop, m => new
        {
            m.WspName,
            m.Remark,
            m.Status,
            m.UpdatedBy,
            m.UpdatedTime,
        }, cancellationToken);
        return Result.From(ok);
    }
}
